package net.lzzy.practices.services;

import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.Chapter;
import net.lzzy.practices.entities.Course;
import net.lzzy.practices.repositories.ChapterRepository;
import net.lzzy.practices.repositories.CourseRepository;
import net.lzzy.practices.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author HUAWEI
 */
@Service
public class ChapterServicesImpl implements ChapterService {
    private final ChapterRepository repository;
    private final CourseRepository cRepository;

    @Autowired
    public ChapterServicesImpl(ChapterRepository repository, CourseRepository cRepository) {
        this.repository = repository;
        this.cRepository = cRepository;
    }

    @Override
    public List<Chapter> getTeachersChapters(UUID courseId) {
        return repository.findChaptersByCourseIdOrderByUpdateTimeDesc(courseId);
    }

    @Override
    public List<Chapter> getStudentsChapters(UUID courseId) {
        return repository.findChaptersByCourseIdAndOpenOrderByUpdateTimeDesc(courseId,true);
    }

    @Override
    public Chapter getById(UUID id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Chapter add(Chapter chapter) {
        return repository.save(chapter);
    }

    @Override
    public Chapter update(Chapter chapter, String token) {
        UUID teacherId=chapter.getCourse().getTeacher().getId();
        if(!teacherId.toString().equals(JwtUtil.verifyToken(token))){
            return null;
        }
        chapter.setUpdateTime(new Date());
        return repository.save(chapter);
    }

    @Override
    public Chapter openCloseChapter(UUID id, boolean open, String token) {
        Chapter chapter = repository.findById(id).orElse(null);
        if(chapter != null) {
            chapter.setOpen(open);
            return repository.save(chapter);
        }
        return null;
    }

    @Override
    public Messages remove(UUID chapterId, UUID courseId,String token) {
//    Course course = cRepository.findById(chapterId).orElse(null);
        Chapter chapter = repository.findById(chapterId).orElse(null);
        if(chapter == null) {
            return Messages.WRONG_ID;
        }
        Course course=cRepository.getById(courseId);
        UUID teacherId=course.getTeacher().getId();
        if (!teacherId.toString().equals(JwtUtil.verifyToken(token))){
            return Messages.NO_PERMISSION;
        }
        if (!chapter.getQuestions().isEmpty()){
            return Messages.RELATED_DATA;
        }
        repository.delete(chapter);
        return Messages.SUCCESS;
    }
}